package com.juyu.miliao.api.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.juyu.miliao.api.dao.mysql.UserInfoDao;
import com.juyu.miliao.api.dao.redis.LineTimeRedisDao;
import com.juyu.miliao.api.domain.Appkey;
import com.juyu.miliao.api.domain.User;
import com.juyu.miliao.api.domain.dto.IntegralLevelAndTitleDTO;
import com.juyu.miliao.api.domain.vo.FindDynamicVO;
import com.juyu.miliao.api.rabbitMQ.UserLoginRobotMessageRabbitMq;
import com.juyu.miliao.common.constant.EnumType;
import com.juyu.miliao.common.constant.SpendSystemMessage;
import com.juyu.miliao.common.constant.SpendSystemMessageType;
import com.juyu.miliao.common.domain.CommonHead;
import com.juyu.miliao.common.netease.NetEaseCloudUserService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class VestRobotMessageService {
    @Resource
    private UserInfoDao userInfoDao;
    @Resource
    private UserLoginRobotMessageRabbitMq userLoginRobotMessageRabbitMq;
    @Resource
    private LineTimeRedisDao lineTimeRedisDao;
    @Resource
    private AppKeyService appKeyService;
    @Resource
    private IntegralLevelInfoService integralLevelInfoService;

    @Autowired
    private ObjectMapper objectMapper;

    private final Logger logger = LoggerFactory.getLogger(VestRobotMessageService.class);
    private static final long robotSendMessageUserId = 12890000;

    /**
     * 给MMJY包在线用户发送 有人送礼物信息
     * @param body
     * @param userIdArray
     */
    public void getSendGiftSpendMessage(String body, Long[] userIdArray) {

        JSONObject bodyJSON = new JSONObject();
        bodyJSON.put("messageType", 2);
        bodyJSON.put("body",body);
        JSONArray jsonArray = JSONArray.fromObject(userIdArray);
        logger.info("发送礼物消息：body:"+body+"---userIdArray:"+jsonArray.toString());
        try {
            String temp = NetEaseCloudUserService.sendBatchAttachMsg(bodyJSON.toString(), jsonArray.toString());
            logger.info("发送礼物消息结果：temp————"+temp);
            if (!temp.substring(temp.indexOf("code") + 6, temp.indexOf("code") + 9).equals("200"))
                logger.error("批量发送点对点自定义系统通知异常-云信：message={}", temp);
        } catch (Exception e) {
            logger.error("批量发送点对点自定义系统通知错误", e);
        }
    }

    /**
     * 发送给主播消息，消息格式: ID：userId，
     *
     * @param userId
     * @param fee
     * @param enumType
     */
    public void getSendMsgByHost(long userId, String fee, EnumType enumType) {
        Set<String> hostSet = lineTimeRedisDao.getHostLineBySex(2);
        Set<Long> userIds = hostSet.stream().map(Long::parseLong).collect(Collectors.toSet());
        List<User> userList = userInfoDao.getVisitorListByUserId(userIds);
//        Appkey appkey = appKeyService.getAppKeyByKey("hostUserStarSendMsg");
//        int hostUserStarSendMsg = Integer.parseInt(appkey.getValue());
        userList = userList.stream().filter(user -> {
            IntegralLevelAndTitleDTO integralLevelAndTitleDTO = integralLevelInfoService
                    .getUserIntegralLevel(user.getIntegralSum());
            return integralLevelAndTitleDTO.getIsUserRechargeReminder()==1;
        }).collect(Collectors.toList());
        if(userList.size()==0){
            return;
        }
        hostSet = userList.stream().map(user -> user.getUserId()+"").collect(Collectors.toSet());
        if (hostSet.size() > 0) {
            User user = userInfoDao.getUserById(userId);
            String msg = SpendSystemMessage.REPORT_USER_SEND_HOST_USER_MESSAGE.getMessage(userId,user.getNickName());
            logger.info("用户充值给主播发送系统通知：userId={},message={}", userId, msg);
            List<String> result = new ArrayList<>(hostSet);
            result.forEach(hostUser -> {
                try {
                    Map<String, Object> map = new HashMap<>();
                    map.put("title", "寻寻");
                    map.put("type", SpendSystemMessageType.REPORT_USER_SEND_HOST_USER_MESSAGE_TYPE.getCode());
                    map.put("message", msg);

                    Map<String,Object> ext = new HashMap<>(1);
                    ext.put("userId",userId);

                    String template = SpendSystemMessage.REPORT_USER_SEND_HOST_USER_MESSAGE.getMessage();
                    String[] colors = SpendSystemMessage.REPORT_USER_SEND_HOST_USER_MESSAGE.getColors();
                    ext.put("template",template);

                    List<String> templateList = new ArrayList<>(1);

                    templateList.add(userId+"");
                    templateList.add(user.getNickName());

                    ext.put("templateValue",templateList);
                    ext.put("templateColors",colors);

                    map.put("ext",ext);
                    ObjectMapper mapper = new ObjectMapper();
                    String createLogInfo= NetEaseCloudUserService.getSystemMessage(mapper.writeValueAsString(map), Long.parseLong(hostUser));
                    if(!createLogInfo.substring(createLogInfo.indexOf("code")+6, createLogInfo.indexOf("code")+9).equals("200")){
                        if(logger.isErrorEnabled()){
                            logger.error("用户充值给主播发送系统消息发送IM失败：系统错误信息" + createLogInfo + "\n" + "参数：" + userId);
                        }

                    }
                } catch (Exception e) {
                    logger.error("用户充值给主播发送系统消息发送IM错误：参数-" + userId,e);
                }
            });
        }
    }



    public void startVestRobotMessage(long userId, CommonHead commonHead) {
        userLoginRobotMessageRabbitMq.userLoginRobotMessageMQ(userId,commonHead);
//        OpenApiDTO dto = openApiService.getOpenApiDTO(commonHead);
//        //机器人消息不为null且机器人消息关闭时才关闭
//        if (dto != null && dto.getApiResourceDTO() != null && !dto.getApiResourceDTO().getRobotMsg()) {
//            return;
//        }
//        // 用户不能为null，不能是主播，包版本不能为null或“”
//        User user = userInfoDao.getUserInfoById(userId);
//        if (user == null)
//            throw new ConsumeRuntimeException("user为空");
//        if (user.getIsHost() == 1)
//            throw new ConsumeRuntimeException("user为主播");
////        UserWallet userWallet = userWalletDao.getUserWalletById(userId);
////        if(userWallet.getDeposit() >0)
////            throw new ConsumeRuntimeException("user金币大于0,不能发送机器人消息");
//        startVestTCYLRobotMessage(userId);
    }


//    //type1文字：取消---0分(2个),10秒间隔6条，5分钟后间隔10秒7条
//    //type2免费图：取消---1.30分
//    //type3付费图：取消
//    //type4视频：10秒，1分钟，3分钟 ，5分钟
//    //type5 弹窗视频：取消
//    private void startVestTCYLRobotMessage(long userId) {
//        JSONObject json = new JSONObject();
//        json.put("type", 4);
//        json.put("packageId", 2);
//        json.put("userId", userId);
//        //发送视频
//        //10发送
////        long timestamp = LocalDateTime.now().plus(10, ChronoUnit.SECONDS).toInstant(ZoneOffset.of("+8")).toEpochMilli();
////        stringRedisTemplate.opsForHash().put("robotMessageScheduled", NumberTool.randomInstant(timestamp), json.toString());
//        //60发送
//        long timestamp = LocalDateTime.now().plus(60 * 2, ChronoUnit.SECONDS).toInstant(ZoneOffset.of("+8")).toEpochMilli();
//        stringRedisTemplate.opsForHash().put("robotMessageScheduled", NumberTool.randomInstant(timestamp), json.toString());
//        //60*3发送
//        timestamp = LocalDateTime.now().plus(60 * 4, ChronoUnit.SECONDS).toInstant(ZoneOffset.of("+8")).toEpochMilli();
//        stringRedisTemplate.opsForHash().put("robotMessageScheduled", NumberTool.randomInstant(timestamp), json.toString());
//        //60*5发送
//        timestamp = LocalDateTime.now().plus(60 * 8, ChronoUnit.SECONDS).toInstant(ZoneOffset.of("+8")).toEpochMilli();
//        stringRedisTemplate.opsForHash().put("robotMessageScheduled", NumberTool.randomInstant(timestamp), json.toString());
//    }

    /**
     * 支付成功，给ios用户发送消息
     *
     * @param userId
     * @param message
     */
    public void getSendMsgByIos(long userId, String message) {
        logger.info("发送充值通知：userId={},message={}", userId, message);

        JSONObject body = new JSONObject();
        body.put("msg", message);
        //开发者扩展字段
        JSONObject ext = new JSONObject();


        try {
            String temp = NetEaseCloudUserService.getSendMsg(userId, robotSendMessageUserId,
                    EnumType.TEXT_MESSAGE.state, body.toString(), ext.toString(), "");

            if (!temp.substring(temp.indexOf("code") + 6, temp.indexOf("code") + 9).equals("200")) {
                logger.error("发送IOS普通消息异常-云信：userId={},message={}", userId, temp);
            }

        } catch (Exception e) {
            logger.error("发送IOS普通消息异常：userId={},error={}", userId, e);
        }
    }

    public void getSendMsg(long userId ,long robotId,String message,String ext,int state) {
        logger.info("发送通知：userId={},robotId={},message={}", userId,robotId,message);
        JSONObject body = new JSONObject();
        body.put("msg", message);

        try {
            String temp = NetEaseCloudUserService.getSendMsg(userId,robotId, state, body.toString(), ext, "");

            if (!temp.substring(temp.indexOf("code") + 6, temp.indexOf("code") + 9).equals("200")) {
                logger.error("发送普通消息异常-云信：userId={},message={}", userId, temp);
            }

        } catch (Exception e) {
            logger.error("发送普通消息异常：userId={},error={}", userId, e);
        }
    }
    public void getSendMsg(long userId ,String message) {
        try {
            logger.info("发送通知：userId={},robotId={},message={}", userId,message);
            Map<String, String> map = new HashMap<String, String>();
            map.put("title", "寻寻");
            map.put("type", "1");
            map.put("message", message);
            ObjectMapper mapper = new ObjectMapper();
            String createLogInfo= NetEaseCloudUserService.getSystemMessage(mapper.writeValueAsString(map), userId);
            if(!createLogInfo.substring(createLogInfo.indexOf("code")+6, createLogInfo.indexOf("code")+9).equals("200")){
                if(logger.isErrorEnabled()){
                    logger.error("充值vip系统消息发送IM失败：系统错误信息" + createLogInfo + "\n" + "参数：" + userId);
                }

            }
        } catch (Exception e) {
            logger.error("充值vip系统消息发送IM错误：参数-" + userId,e);
        }
    }

    /**
     * 发送系统消息带扩展
     * @param userId 用户
     * @param message 消息
     * @param type 消息类型
     * @param ext 扩展内容
     */
    public void getSendMsg(long userId ,String message,String type,Map<String,Object> ext) {
        try {
            logger.info("发送通知：userId={},robotId={},message={},type={},ext={}", userId,message,type,ext);
            Map<String, Object> map = new HashMap<>();
            map.put("title", "寻寻");
            map.put("type", type);
            map.put("message", message);
            map.put("ext",ext);
            String createLogInfo= NetEaseCloudUserService.getSystemMessage(objectMapper.writeValueAsString(map), userId);
            if(!createLogInfo.substring(createLogInfo.indexOf("code")+6, createLogInfo.indexOf("code")+9).equals("200")){
                if(logger.isErrorEnabled()){
                    logger.error("发送自定义系统消息发送IM失败：系统错误信息" + createLogInfo + "\n" + "参数：" + userId);
                }

            }
        } catch (Exception e) {
            logger.error("自定义系统消息发送IM错误：参数-" + userId,e);
        }
    }
    /**
     *  系统补偿vip发送系统消息
     * @param userId
     * @param message
     */
    public void getSendMsgBySystem(long userId,String message) {

        try {
            logger.info("发送通知：userId={},robotId={},message={}", userId,message);
            Map<String, String> map = new HashMap<String, String>();
            map.put("title", "寻寻");
            map.put("type", "1");
            map.put("message", message);
            ObjectMapper mapper = new ObjectMapper();
            String createLogInfo= NetEaseCloudUserService.getSystemMessage(mapper.writeValueAsString(map), userId);
            if(!createLogInfo.substring(createLogInfo.indexOf("code")+6, createLogInfo.indexOf("code")+9).equals("200")){
                if(logger.isErrorEnabled()){
                    logger.error("充值vip系统消息发送IM失败：系统错误信息" + createLogInfo + "\n" + "参数：" + userId);
                }

            }
        } catch (Exception e) {
            logger.error("充值vip系统消息发送IM错误：参数-" + userId,e);
        }
        //        JSONObject body = new JSONObject();
//        body.put("msg", message);
//
//        try {
//            String temp = NetEaseCloudUserService.getSendMsg(userId,robotId, state, body.toString(), ext, "");
//
//            if (!temp.substring(temp.indexOf("code") + 6, temp.indexOf("code") + 9).equals("200")) {
//                logger.error("发送普通消息异常-云信：userId={},message={}", userId, temp);
//            }
//
//        } catch (Exception e) {
//            logger.error("发送普通消息异常：userId={},error={}", userId, e);
//        }
    }

    public void getSendMsgByIosToH5(long userId, String message) {
        logger.info("发送充值通知：userId={},message={}", userId, message);

        JSONObject body = new JSONObject();
        body.put("msg", message);
        //开发者扩展字段
        JSONObject ext = new JSONObject();


        try {
            String temp = NetEaseCloudUserService.getSendMsg(userId, EnumType.HELPER_USER_ID.state,
                    EnumType.TEXT_MESSAGE.state, body.toString(), ext.toString(), "");

            if (!temp.substring(temp.indexOf("code") + 6, temp.indexOf("code") + 9).equals("200")) {
                logger.error("发送IOS普通消息异常-云信：userId={},message={}", userId, temp);
            }

        } catch (Exception e) {
            logger.error("发送IOS普通消息异常：userId={},error={}", userId, e);
        }
    }

    /**
     * 提问完成发送消息
     *
     * @param userId
     * @param message
     */
    public void questionCompletionSendMsg(long userId, String message) {
        logger.info("提问完成发送消息：{}，给用户：{}", message, userId);
        JSONObject body = new JSONObject();
        body.put("msg", message);
        try {
            String temp = NetEaseCloudUserService.getSendMsg(userId, robotSendMessageUserId,
                    EnumType.TEXT_MESSAGE.state, body.toString(), new JSONObject().toString(), "");
            if (!temp.substring(temp.indexOf("code") + 6, temp.indexOf("code") + 9).equals("200")) {
                logger.error("发送普通消息异常-云信：userId={},message={}", userId, temp);
            }
        } catch (Exception e) {
            logger.error("发送普通消息异常：userId={},error={}", userId, e);
        }
    }

    /**
     * 提问问题或或回答问题发送消息
     *
     * @param toUserId
     * @param fromUser
     * @param message
     */
    public void questionOrAnswerSendMsg(long toUserId, long fromUser, String message) {
        logger.info("提问问题或或回答问题发送消息,用户：{},发送消息：{},给用户：{}", fromUser, message, toUserId);
        JSONObject body = new JSONObject();
        body.put("msg", message);
        try {
            String temp = NetEaseCloudUserService.getSendMsg(toUserId, fromUser,
                    EnumType.TEXT_MESSAGE.state, body.toString(), new JSONObject().toString(), "");

            if (!temp.substring(temp.indexOf("code") + 6, temp.indexOf("code") + 9).equals("200")) {
                logger.error("发送普通消息异常-云信：toUserId={},fromUser={},message={}", toUserId, fromUser, temp);
            }
        } catch (Exception e) {
            logger.error("发送普通消息异常：toUserId={},fromUser={},error={}", toUserId, fromUser, e);
        }
    }
}
